package xyz.lne.researchgroupmanage.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import xyz.lne.researchgroupmanage.annotation.AnonymousGetMapping;
import xyz.lne.researchgroupmanage.annotation.AnonymousPostMapping;
import xyz.lne.researchgroupmanage.common.CommonResponse;
import xyz.lne.researchgroupmanage.controller.response.UserSimpleResponse;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.service.SysUserService;
import xyz.lne.researchgroupmanage.service.UserResearchService;
import xyz.lne.researchgroupmanage.service.dataTransferObject.UserResearchDTO;
import xyz.lne.researchgroupmanage.util.SecurityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author team7
 * @since 2021-01-19
 */
@RestController
@RequestMapping("/user-research")
public class UserResearchController {

    @Autowired
    private UserResearchService userResearchService;

    @Autowired
    private SysUserService sysUserService;

    @AnonymousGetMapping("/getUserListInResearch")
    List<UserSimpleResponse> findUsersByresearch(Integer researchId){
        List<UserResearchDTO> list= userResearchService.findUsersByresearch(researchId);

        if(list.isEmpty()) {
            return new ArrayList<>();
        }
        else {
            return list.stream().map(i->convertIdToSimpleResponse(i.getUserId()))
                    .distinct().collect(Collectors.toList());
        }
    }

    @AnonymousGetMapping("/getParticularUserListInResearch")
    List<UserSimpleResponse> findParticularUserList(Integer researchId,String userName){
        List<UserSimpleResponse> list=findUsersByresearch(researchId);

       return list.stream().filter(i->isLike(userName,i.getUserName())).collect(Collectors.toList());
    }

    private UserSimpleResponse convertIdToSimpleResponse(Integer userId){
        return new UserSimpleResponse(userId,sysUserService.findNameById(userId));
    }

    private Boolean isLike(String inputName,String userName){
        return userName.contains(inputName);
    }

    @AnonymousPostMapping("/applyToResearch")
    CommonResponse userApplyToResearch(Integer researchId){
        try {
            userResearchService.applyToResearch(researchId,SecurityUtils.getCurrentUserId());
            return CommonResponse.create("success");
        }catch (BadRequestException e) {
            e.printStackTrace();
            System.out.println(e.getData());
        }

        return CommonResponse.Failed();
    }
}

